#include <sys/syscall.h>

long (*syscall[NUM_SYSCALLS])();

void handle_syscall(regs_context_t *regs, uint64_t interrupt, uint64_t cause)
{
    /* TODO: [p2-task3] handle syscall exception */
    /**
     * HINT: call syscall function like syscall[fn](arg0, arg1, arg2),
     * and pay attention to the return value and sepc
     */
     int syscall_num = (int)(*(reg_t*)((ptr_t)regs + 136));//a7
     int parameter_0 = (int)(*(reg_t*)((ptr_t)regs + 80)); //a0
     int parameter_1 = (int)(*(reg_t*)((ptr_t)regs + 88)); //a1
     int parameter_2 = (int)(*(reg_t*)((ptr_t)regs + 96)); //a2
     int parameter_3 = (int)(*(reg_t*)((ptr_t)regs + 104));//a3
     int parameter_4 = (int)(*(reg_t*)((ptr_t)regs + 112));//a4
     
     
     long return_value;
     return_value = syscall[syscall_num](parameter_0,parameter_1,parameter_2,parameter_3,parameter_4);
     
     //store the return value in a0
     *(reg_t*)((ptr_t)regs + 80) = return_value; 
     
     //set sepc+4 to sepc
     reg_t sepc_value = *(reg_t*)((ptr_t)regs + 264); 
     *(reg_t*)((ptr_t)regs + 264) = sepc_value + 4;
     
     
     
}
